package com.lhy.mymall.flter;

import com.lhy.mymall.common.Constant;
import com.lhy.mymall.pojo.User;
import com.lhy.mymall.service.UserService;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: 卢辉宇
 * @date: 2022/12/14 21:48
 * @description: 用户过滤器，用于判断是否是用户登录的
 */
public class UserFilter implements Filter {


    //定义一个静态的user对象，用于保存当前用户的信息
    public static User currentUser;

    @Resource
    UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //解决响应中文乱码问题
        servletResponse.setContentType("json/application;charset=UTF-8");

        //通过servletRequest的子接口拿到session
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        //通过session保存的信息判断是否登录
         currentUser = (User)session.getAttribute(Constant.MALL_USER);
        //判断是否登录
        if (currentUser==null){
            //通过HttpServletResponseWrapper的对象返回json数据给前端
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            //向前端返回的json数据
            out.write("{\"status\":1007,\"msg\":\"用户未登录\",\"data\":null}");
            //刷新并关闭
            out.flush();
            out.close();
            //不放行，提前结束
            return;
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
